<?php

namespace app\api\middleware;

use app\api\model\Article as ModelArticle;
use app\api\service\Token;
use app\api\validate\Article as ValidateArticle;
use think\exception\ValidateException;
use think\facade\Db;

class Article
{
    public function handle($request, \Closure $next)
    {
        $param = input();
        $token = isset($param['token']) ? $param['token'] : request()->header('token');
        $action = $request->action();
        $user = (new Token)->getTokenVal($token);
        try {
            if ($action == 'edit') {
                validate(ValidateArticle::class)->scene('edit')->check($param);
                $hasArt = ModelArticle::where(['id' => $param['id'], 'user_id' => $user['id']]);
                if ($hasArt->findOrEmpty()->isEmpty()) return error('文章不存在或已被删除');
                $art = $hasArt->find();
                if ($art->status == 2) return error('文章已被锁定，无法修改');
                // 文章ID
                if ($art['type'] != 1 && empty($param['hide_content'])) {
                    return error('隐藏内容不能为空', 201);
                }
                if ($art['type'] == 2 && @$param['score'] == '') {
                    return error('阅读积分设置不能为空', 201);
                }
                $data = [
                    'title' => $param['title'],
                    'content' => $param['content'],
                    'score' => $param['score'],
                    'id' => $param['id'],
                    'hide_content' => $param['hide_content'],
                    'images' => @$param['images'],
                    'status' => 0
                ];
            } else {
                validate(ValidateArticle::class)->scene('add')->check($param);
                // 判断是否存在分类
                $cate = Db::name('category')->where(['id' => $param['cate_id'], 'status' => 1])->find();
                if (!$cate) return error('分类不存在');
                if ($param['type'] != 1 && empty($param['hide_content'])) {
                    return error('隐藏内容不能为空', 201);
                }
                if ($param['type'] == 2 && @$param['score'] == '') {
                    return error('阅读积分设置不能为空', 201);
                }
                $data = [
                    'title' => $param['title'],
                    'cate_id' => $param['cate_id'],
                    'content' => $param['content'],
                    'status' => 0,
                    'type' => $param['type'],
                    'score' => $param['type'] == 2 ? @$param['score'] : 0,
                    'hide_content' => @$param['hide_content'],
                    'images' => @$param['images']
                ];
            }


            $request->param = $data;
        } catch (ValidateException $e) {
            return error($e->getError(), 201);
        }

        return $next($request);
    }
}
